#define _CRT_SECURE_NO_WARNINGS 1

#include "Seqlist.h"

void SLInit(SL* psl)
{
	assert(psl != NULL);
	psl->a = (SLDataType*)malloc(sizeof(SLDataType) * 4);
	if (psl->a == NULL)
	{
		perror("malloc fail!");
		exit(1);
	}
	psl->capacity = 4;
	psl->size = 0;
}

void SLDestroy(SL* psl)
{
	assert(psl != NULL);
	free(psl->a);
	psl->a = NULL;
	psl->size = psl->capacity = 0;
}

void CheckCapacity(SL* psl)
{
	assert(psl != NULL);
	if (psl->size == psl->capacity)
	{
		SLDataType* temp = (SLDataType*)realloc(psl->a, sizeof(SLDataType) * psl->capacity * 2);
		if (temp == NULL)
		{
			perror("realloc fail!\n");
			exit(1);
		}
		psl->a = temp;
		psl->capacity *= 2;
	}
}

void SLPrint(SL* psl)
{
	assert(psl != NULL);
	for (int i = 0; i < psl->size; i++)
	{
		printf("%d ", psl->a[i]);
	}
	printf("\n");
}

void SLPushBack(SL* psl, SLDataType x)
{
	assert(psl != NULL);
	CheckCapacity(psl);
	psl->a[psl->size++] = x;
}

void SLPushFront(SL* psl, SLDataType x)
{
	assert(psl != NULL);
	CheckCapacity(psl);
	for (int i = psl->size; i > 0; i--)
	{
		psl->a[i] = psl->a[i - 1];
	}
	psl->a[0] = x;
	psl->size++;
}

void SLPopBack(SL* psl)
{
	assert(psl != NULL);
	assert(psl->size > 0);
	psl->size--;
}

void SLPopFront(SL* psl)
{
	assert(psl != NULL);
	assert(psl->size > 0);
	int begin = 0;
	for (int i = begin; i < psl->size - 1; i++)
	{
		psl->a[i] = psl->a[i + 1];
	}
	psl->size--;
}

void SLInsert(SL* psl, SLDataType x, int pos)
{
	assert(psl != NULL);
	assert(pos >= 0 && pos <= psl->size);
	CheckCapacity(psl);

	int end = psl->size-1;
	for (int i = end; i >= pos; i--)
	{
		psl->a[i+1] = psl->a[i];
	}
	psl->a[pos] = x;
	psl->size++;
}

void SLErase(SL* psl, int pos)
{
	assert(psl != NULL);
	assert(pos >= 0 && pos < psl->size);

	int begin = pos;
	for (int i = begin; i < psl->size-1; i++)
	{
		psl->a[i] = psl->a[i+1];
	}
	psl->size--;
}

int SLFind(SL* psl, SLDataType x)
{
	assert(psl != NULL);
	for (int i = 0; i < psl->size; i++)
	{
		if (psl->a[i] == x)
		{
			return i;
		}
	}
	return -1;
}

void SLModify(SL* psl, int pos, SLDataType x)
{
	assert(psl != NULL);
	assert(pos >= 0 && pos < psl->size);
	psl->a[pos] = x;
}